package com.ysx.filter;

import com.ysx.common.constants.SystemConstants;
import com.ysx.common.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器(模拟登录校验token token携带方式采用get地址栏的方式)
 */
@Component
public class CustomVeMediaGlobalFilter implements GlobalFilter, Ordered {
    //做具体的逻辑操作
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1,判断请求路径中是否包含登录或者注册 有则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String uri = request.getURI().toString();
        if (!StringUtils.isEmpty(uri) && (uri.contains("/wmUser/login") ||uri.endsWith("v2/api-docs"))) {
           return   chain.filter(exchange);
        }
        //2,没有 获取请求头的信息 判断是否存在token 有则继续
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3,根据token信息 调用jjwt方法 判断token状态 通过则继续
        int tokenStatus = AppJwtUtil.verifyToken(token);
        if(tokenStatus!= SystemConstants.JWT_OK){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //4,路由到微服务
        request.mutate().header(SystemConstants.WEMEDIA_HEADER_USERID,claimsBody.get("id").toString());
        return chain.filter(exchange);
    }
    //设置过滤器级别 数字越小级别越高
    @Override
    public int getOrder() {
        return -1;
    }
}